<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Comment;
use addons\qingdongams\model\Contacts;
use addons\qingdongams\model\CustomerProduct;
use addons\qingdongams\model\Event;
use addons\qingdongams\model\File;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\WorkorderFile;
use think\Db;
use think\Exception;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 * 工单
 */
class WebWorkorder extends WebIndexApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];
    /**
     * @var \addons\qingdongams\model\Workorder
     */
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new \addons\qingdongams\model\Workorder();

    }

    //获取购买过的客户产品列表/ 所有客户产品列表
    public function getProductList()
    {
        if ($this->personInfo['customer_id']) {
            $list = CustomerProduct::alias('c')->where(['c.customer_id' => $this->personInfo['customer_id']])
                ->join('qingdongams_product p', 'p.id=c.product_id', 'left')
                ->field('c.id,c.number,p.name,p.img,p.unit,p.price,c.status')->select();
            if (count($list) > 0) {
                $this->success('请求成功', $list);
            }
        }
        $this->success('暂未查询到您购买过公司产品，请联系业务员确定！');
    }

    //获取工单编号
    public function getWorkorderNumber()
    {
        $this->success('请求成功', ['number' => $this->model::getWorkorderNumber()]);
    }

    //添加工单
    public function addWorkorder()
    {
        $params = $this->request->post();
        if ($this->model::where([
            'workorder_number' => $params['workorder_number'],
        ])->find()) {
            $this->error('工单编号已存在');
        }
        if ($this->personInfo['customer_id']) {
            $productIds = CustomerProduct::alias('p')->where(['p.id' => $params['customer_product_id']])
                ->join('qingdongams_customer c', 'c.id=p.customer_id', 'left')->field('p.contract_id,c.owner_staff_id')->find();
            $contacts = Contacts::where(['customer_id' => $this->personInfo['customer_id']])->find();
            $params['customer_id'] = $this->personInfo['customer_id'];//客户Id
            $params['contract_id'] = $productIds['contract_id'];// 订单id
            $params['contacts_id'] = $contacts['id'];// 联系人id
        } else {
            $this->error('暂未查询到您购买过公司产品,抱歉暂不能提交工单!');
        }
        if (strtotime($params['appointment_time']) <= time()) {
            $this->error('时间不得早于当前');
        }
        $params['appointment_time'] = date("Y-m-d H:i:s", strtotime($params['appointment_time']));
        if (!$params['linkman'] || !$params['linkfun']) {
            $this->error('联系人不能为空');
        }
        // 表单验证
        if (($result = $this->validate($params, 'addons\qingdongams\validate\Workorder.create')) !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $params['create_type'] = 2;// 1是员工提出，2联系人提出
            $params['person_id'] = $this->personId;
            $params['workorder_type'] = '上门维修';
            $result = $this->model::createCustomerWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加工单成功');
        }
    }

    //获取工单列表
    public function getOrderList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        $where = [];
        $type = input('type', 0);//状态 0全部 1 处理中 2 已完成
        $where1['customer_id'] = $this->personInfo['customer_id'];
        $where1['workorder_type'] = '上门维修';
        $where2['person_id'] = $this->personId;
        if ($type == 1) {
            $where['status'] = ['in', '0,1,2'];
        } elseif ($type == 2) {
            $where['status'] = ['in','3,9'];
        } else if ($type != 0) {
            $this->error('状态错误');
        }
        if (isset($params['name']) && $params['name']) {//查询名称
            $where['title|workorder_number'] = ['like', "%{$params['name']}%"];
        }
        $list = $this->model::where($where)->where(function ($query) use ($where1, $where2) {
            return $query->where($where1)->whereor($where2);
        })->with([
            'comments',
            'ownerStaff',
        ])->order('id desc')->field('deletetime,updatetime', true)->paginate($limit);

        $this->success('请求成功', $list);
    }

    // 工单详情
    public function detail()
    {
        $id = input('id');
        if (!$id) {
            $this->error('参数不能为空！');
        }
        $detail = $this->model::where('id', $id)->with([
            'comments',
            'person',
            'ownerStaff',
            'contacts'
        ])->field('deletetime,updatetime', true)->find();
        $files = WorkorderFile::where(['workorder_id' => $id])->column('file_id');
        $detail['linkman'] = $detail['linkman'] ?? $detail['contacts']['name'];
        $detail['linkfun'] = $detail['linkfun'] ?? $detail['contacts']['mobile'];
        $detail['file'] = [];
        if ($files) {
            $detail['file'] = File::where('id', 'in', $files)->select();
        }
        $this->success('', $detail);
    }


    // 评论的列表
    public function commentList()
    {
        $id = input('id');
        if (!$id) {
            $this->error('参数不能为空');
        }
        $commentModel = new Comment();
        $where = [
            'relation_id' => $id,
            'relation_type' => 'workorder',
        ];
        $list = $commentModel->where($where)->select();
        $this->success('', $list);

    }

    //添加评论
    public function addComment()
    {
        $content = input('content');
        $record_id = input('record_id');// 工单Id
        $relation_type = input('relation_type', 'workorder');
        if (empty($content)) {
            $this->error('评论内容不能为空');
        }
        $data = [
            'relation_type' => $relation_type,
            'relation_id' => $record_id,
            'staff_id' => $this->personId,
            'content' => $content,
            'status' => 1,
            'ip' => get_client_ip(),
        ];
        $commentModel = new Comment();
        Db::startTrans();
        try {
            $commentModel->save($data);
            if ($relation_type == $commentModel::WORKORDER_TYPE) {
                $record = $this->model->where(['id' => $record_id])->find();
            }
            if (empty($record)) {
                $this->error('记录不存在');
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('评论成功');
    }


    // 获取评价工单列表
    public function get_finish_list()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        $type = $this->request->post('type', 1);// 1 已评价  2 未评价

        $where = [
            'customer_id' => $this->personInfo['customer_id'],
            'workorder_type' => '上门维修',
            'status' => 3,
        ];
        if (isset($params['name']) && $params['name']) {//查询名称
            $where['title|workorder_number'] = ['like', "%{$params['name']}%"];
        }
        if ($type == 1) {
            $where['is_resolved'] = ['not null', ['neq', ''], 'and'];
        } else {
            $where['is_resolved'] = ['null', '', 'and'];
        }
        $list = $this->model::where($where)->with([
            'comments',
            'ownerStaff'
        ])->order('id desc')->field('deletetime,updatetime', true)->paginate($limit);
        $this->success('请求成功', $list);
    }

    // 评价工单
    public function addEvaluate()
    {
        $id = input('id');
        if (!$id) {
            $this->error('参数错误！');
        }
        $info = $this->model->where('id', $id)->find();
        if ($info['customer_id'] != $this->personInfo['customer_id']) {
//            $this->error('您不是客户，无权评价!');
        }
        $save = [];
        $save['is_resolved'] = $this->request->post('is_resolved', 1);
        $save['comment_score'] = $this->request->post('comment_score', 5);
        $save['comment_content'] = $this->request->post('comment_content', '');
        $save['comment_files'] = $this->request->post('comment_files', '');
        if (!isset($save['comment_content']) || empty($save['comment_content'])) {
            $this->error('请输入评价内容');
        }
        $save['status'] = 3;
        if ($info->save($save)) {
            //日程完成
            Event::where(['relation_type' => 'workorder', 'relation_id' => $id])->update(['status' => 2]);

            $this->success('评论成功');
        }

        $this->error('评论失败');
    }
}
